package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增地址簿
     *
     * @param addressBook
     */
    @Override
    public void addAddress(AddressBook addressBook) {
        Long currentId = BaseContext.getCurrentId();
        addressBook.setUserId(currentId);
        addressBook.setIsDefault(0);
        addressBookMapper.addAddress(addressBook);
    }

    /**
     * 查询当前登录用户的所有地址信息
     *
     * @return
     */
    @Override
    public List<AddressBook> getAddressByUser() {
        Long currentId = BaseContext.getCurrentId();
        List<AddressBook> addressBook = addressBookMapper.getAddressByUser(currentId);
        return addressBook;
    }

    /**
     * 查询默认地址
     *
     * @return
     */
    @Override
    public AddressBook getDefault() {
        AddressBook addressBook = addressBookMapper.getDefault(BaseContext.getCurrentId());
        return addressBook;
    }

    /**
     * 根据id修改地址
     *
     * @param addressBook
     */
    @Override
    public void updateAddress(AddressBook addressBook) {
        addressBookMapper.updateAddress(addressBook);
    }

    /**
     * 根据id删除地址
     *
     * @param id
     */
    @Override
    public void deleteByid(Long id) {
        addressBookMapper.deleteByid(id);
    }

    /**
     * 根据id查询地址
     *
     * @param id
     * @return
     */
    @Override
    public AddressBook queryByid(Long id) {
        AddressBook addressBook = addressBookMapper.queryByid(id);
        return addressBook;
    }

    /**
     * 设置默认地址
     *
     * @param id
     */
    @Override
    public void setDefault(Long id) {
        //先将所有默认地址设为0
        AddressBook addressBook = AddressBook.builder()
                .isDefault(0)
                .userId(BaseContext.getCurrentId())
                .build();
        addressBookMapper.setDefalutTo(addressBook);
        //修改
        addressBookMapper.setDefalut(id);
    }
}
